<template>
  <div class="category-form">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>{{ isEdit ? '编辑分类' : '添加分类' }}</h2>
      <el-button @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
        返回列表
      </el-button>
    </div>

    <!-- 表单区域 -->
    <div class="form-section">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="category-form-content"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类名称" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="请输入分类名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类编码" prop="code">
              <el-input
                v-model="formData.code"
                placeholder="请输入分类编码"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="父级分类" prop="parentId">
              <el-select 
                v-model="formData.parentId" 
                placeholder="请选择父级分类" 
                style="width: 100%"
                clearable
              >
                <el-option label="无（顶级分类）" :value="null" />
                <el-option
                  v-for="category in parentCategories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="formData.sort"
                :min="0"
                :step="1"
                style="width: 100%"
                placeholder="请输入排序值"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="分类描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入分类描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            <el-icon><Check /></el-icon>
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button @click="goBack">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Check, Refresh, Close } from '@element-plus/icons-vue'
import categoryApi from '@/api/category'

const router = useRouter()
const route = useRoute()

// 表单引用
const formRef = ref(null)

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 提交状态
const submitting = ref(false)

// 父级分类列表
const parentCategories = ref([])

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  code: '',
  parentId: null,
  sort: 0,
  status: 1,
  description: ''
})

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '分类名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类编码', trigger: 'blur' },
    { min: 1, max: 20, message: '分类编码长度在 1 到 20 个字符', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9_]+$/, message: '分类编码只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', min: 0, message: '排序值必须大于等于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 返回列表
const goBack = () => {
  router.push('/category')
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  if (!isEdit.value) {
    // 新增模式下重置为默认值
    Object.assign(formData, {
      id: null,
      name: '',
      code: '',
      parentId: null,
      sort: 0,
      status: 1,
      description: ''
    })
  }
}

// 获取父级分类列表
const getParentCategories = async () => {
  try {
    const result = await categoryApi.getList({ pageSize: 1000 })
    if (result && result.result) {
      // 过滤掉当前分类（编辑模式下）
      parentCategories.value = result.result.filter(item => 
        !isEdit.value || item.id !== parseInt(route.params.id)
      )
    }
  } catch (error) {
    console.error('获取父级分类列表失败:', error)
  }
}

// 获取分类详情
const getCategoryDetail = async (id) => {
  try {
    const result = await categoryApi.getById(id)
    if (result) {
      Object.assign(formData, result)
    }
  } catch (error) {
    ElMessage.error('获取分类详情失败: ' + error.message)
    goBack()
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    const valid = await formRef.value?.validate()
    if (!valid) return

    submitting.value = true

    if (isEdit.value) {
      // 编辑模式
      await categoryApi.update(formData)
      ElMessage.success('更新分类成功')
    } else {
      // 新增模式
      await categoryApi.add(formData)
      ElMessage.success('添加分类成功')
    }

    goBack()
  } catch (error) {
    ElMessage.error((isEdit.value ? '更新' : '添加') + '分类失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

// 组件挂载时的操作
onMounted(async () => {
  await getParentCategories()
  
  if (isEdit.value && route.params.id) {
    getCategoryDetail(route.params.id)
  }
})
</script>

<style scoped>
.category-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-section {
  background: #fff;
  padding: 30px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.category-form-content {
  max-width: 800px;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>
